import TencentCloudChat, { ChatSDK } from '@tencentcloud/chat'
import { AppKey, SDKAppID } from '@/common/tencent.ts'
import TIMUploadPlugin from 'tim-upload-plugin'
import { useMitt } from '@/hooks/useMitt.ts'
import { genTestUserSig } from '@tencentcloud/chat-uikit-vue/debug'
import { isNull } from 'lodash-es'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'

export const useTencentChat = defineStore(
  'TencentChat',
  () => {
    let chat = ref<ChatSDK | null>(null)
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    const appWindow = WebviewWindow.getCurrent().label
    const tencentConversationStore = useTencentConversationStore()

    if (isNull(chat.value) && appWindow === 'home') {
      chat.value = TencentCloudChat.create({ SDKAppID: SDKAppID })
      chat.value.setLogLevel(0)
      chat.value.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })

      localStorage.setItem('TIM_INIT', '1')
      // 监听会话列表更新事件
      chat.value.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, (event: any) => {
        useMitt.emit(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.CONVERSATION_GROUP_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.CONVERSATION_GROUP_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.SDK_READY, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.SDK_READY, event)
      })

      chat.value.on(TencentCloudChat.EVENT.SDK_NOT_READY, function (event: any) {
        console.log('SDK未登录')
        // 登录
        useMitt.emit(TencentCloudChat.EVENT.SDK_NOT_READY, event)

        if (!chat.value?.isReady() && currentUser?.isSign) {
          login(currentUser.userInfo.UserId)
        }
      })

      chat.value.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, (event: any) => {
        console.log('接收未读信息更新', event.data)
        useMitt.emit(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, event)
        tencentConversationStore.totalUnreadMessageCount = event.data
      })

      // 修改消息
      chat.value.on(TencentCloudChat.EVENT.MESSAGE_MODIFIED, function (event: any) {
        // event.data - 存储被修改过的 Message 对象的数组 - [Message]
        useMitt.emit(TencentCloudChat.EVENT.MESSAGE_MODIFIED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.GROUP_COUNTER_UPDATED, function (event: any) {
        console.log('接收群成员更新', event)
        useMitt.emit(TencentCloudChat.EVENT.GROUP_COUNTER_UPDATED, event)
      })

      // 接收消息
      chat.value.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, async function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.MESSAGE_RECEIVED, event)
      })

      // 撤回消息
      chat.value.on(TencentCloudChat.EVENT.MESSAGE_REVOKED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.MESSAGE_REVOKED, event)
      })

      // 用户被踢下线时触发
      chat.value.on(TencentCloudChat.EVENT.KICKED_OUT, function (event: any) {
        console.log('登录被踢出', event.data.type)
        useMitt.emit(TencentCloudChat.EVENT.KICKED_OUT, event)
        // TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT(Web端，同一账号，多页面登录被踢)
        // TencentCloudChat.TYPES.KICKED_OUT_MULT_DEVICE(同一账号，多端登录被踢)
        // TencentCloudChat.TYPES.KICKED_OUT_USERSIG_EXPIRED(签名过期)
        // TencentCloudChat.TYPES.KICKED_OUT_REST_API(REST API kick 接口踢出)
        // window.$message.warning('您的账号已在其他地方登录')
      })

      // 对端已读消息的通知
      chat.value.on(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, function (event: any) {
        // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
        useMitt.emit(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, event)
      })

      // 消息的已读回执通知
      chat.value.on(TencentCloudChat.EVENT.MESSAGE_READ_RECEIPT_RECEIVED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.MESSAGE_READ_RECEIPT_RECEIVED, event)
        // event.data - 存储消息已读回执信息的数组
        // const readReceiptInfoList = event.data
        // readReceiptInfoList.forEach((item) => {
        //   const { groupID, userID, messageID, readCount, unreadCount, isPeerRead } = item
        //   // messageID - 消息 ID
        //   // userID - C2C 消息接收方
        //   // isPeerRead - C2C 消息对端是否已读
        //   // groupID - 群组 ID
        //   // readCount - 群消息已读人数
        //   // unreadCount - 群消息未读人数
        //   const message = chat.value.findMessage(messageID)
        //   if (message) {
        //     if (message.conversationType === TencentCloudChat.TYPES.CONV_C2C) {
        //       if (message.readReceiptInfo.isPeerRead === true) {
        //         // 对端已读
        //       }
        //     } else if (message.conversationType === TencentCloudChat.TYPES.CONV_GROUP) {
        //       if (message.readReceiptInfo.unreadCount === 0) {
        //         // 全部已读
        //       } else {
        //         // message.readReceiptInfo.readCount - 消息最新的已读数
        //         // 如果想要查询哪些群成员已读了此消息，请使用 [getGroupMessageReadMemberList] 接口
        //       }
        //     }
        //   }
        // })
      })

      // 创建群聊
      chat.value.on(TencentCloudChat.EVENT.GROUP_LIST_UPDATED, (event: any) => {
        useMitt.emit(TencentCloudChat.EVENT.GROUP_LIST_UPDATED, event)
      })

      // 群属性更新时触发
      chat.value.on(TencentCloudChat.EVENT.GROUP_ATTRIBUTES_UPDATED, function (event: any) {
        // const groupID = event.data.groupID // 群组ID
        // const groupAttributes = event.data.groupAttributes // 更新后的群属性
        useMitt.emit(TencentCloudChat.EVENT.GROUP_ATTRIBUTES_UPDATED, event)
      })

      // 自己或好友的资料发生变更时触发
      chat.value.on(TencentCloudChat.EVENT.PROFILE_UPDATED, function (event: any) {
        console.log(event.data) // 包含 Profile 对象的数组
        useMitt.emit(TencentCloudChat.EVENT.PROFILE_UPDATED, event)
      })

      // 已订阅用户或好友的状态变更（在线状态或自定义状态）时触发
      chat.value.on(TencentCloudChat.EVENT.USER_STATUS_UPDATED, function (event: any) {
        console.log('user status updated', event.data)
        // const userStatusList = event.data
        // userStatusList.forEach((item) => {
        //   const { userID, statusType, customStatus } = item
        //   // userID - 用户 ID
        //   // statusType - 用户状态，枚举值及说明如下：
        //   // TencentCloudChat.TYPES.USER_STATUS_UNKNOWN - 未知 0
        //   TencentCloudChat.TYPES.USER_STATUS_ONLINE // - 在线 1
        //   // TencentCloudChat.TYPES.USER_STATUS_OFFLINE - 离线 2
        //   // TencentCloudChat.TYPES.USER_STATUS_UNLOGINED - 未登录 3
        //   // customStatus - 用户自定义状态
        // })
        useMitt.emit(TencentCloudChat.EVENT.USER_STATUS_UPDATED, event)
      })

      // 网络状态发生改变
      chat.value.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.NET_STATE_CHANGE, event)
        // event.data.state 当前网络状态，枚举值及说明如下：
        // TencentCloudChat.TYPES.NET_STATE_CONNECTED - 已接入网络
        // TencentCloudChat.TYPES.NET_STATE_CONNECTING
        // 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
        // TencentCloudChat.TYPES.NET_STATE_DISCONNECTED
        // 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
      })

      chat.value.on(TencentCloudChat.EVENT.FRIEND_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.FRIEND_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.FRIEND_GROUP_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.FRIEND_GROUP_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.FRIEND_APPLICATION_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.FRIEND_APPLICATION_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.TOPIC_CREATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.TOPIC_CREATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.TOPIC_DELETED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.TOPIC_DELETED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.TOPIC_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.TOPIC_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.BLACKLIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.BLACKLIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.MY_FOLLOWING_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.MY_FOLLOWING_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.MY_FOLLOWERS_LIST_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.MY_FOLLOWERS_LIST_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.ALL_RECEIVE_MESSAGE_OPT_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.ALL_RECEIVE_MESSAGE_OPT_UPDATED, event)
      })

      chat.value.on(TencentCloudChat.EVENT.PINNED_GROUP_MESSAGE_UPDATED, function (event: any) {
        useMitt.emit(TencentCloudChat.EVENT.PINNED_GROUP_MESSAGE_UPDATED, event)
      })

      // 销毁 SDK 实例。SDK 会先 logout，然后断开 WebSocket 长连接，并释放资源
      // chat.value.destroy()
    }

    const getGenUserSig = (userID: string) => {
      return genTestUserSig({ SDKAppID: SDKAppID, secretKey: AppKey, userID: userID })
    }

    const login = async (userId: string) => {
      const genUserSig = getGenUserSig(userId)
      await chat.value?.login({ userID: userId, userSig: genUserSig.userSig })
        .then(async (res) => {
          console.log('TIMSdk 登录成功')
          // window.alert('TIMSDK 登录成功')
          if (res.data.repeatLogin === true) {
            console.log(res.data.errorInfo)
          }
        })
        .catch((error) => {
          console.warn('login error:', error)
          window.alert(`TIMSdk 登录失败: ${error}`)
        })
    }

    if (!chat.value?.isReady() && currentUser?.isSign) {
      login(currentUser.userInfo.UserId)
    }

    const logout = async () => {
      await chat.value?.logout()
    }

    const destroy = async () => {
      await chat.value?.destroy()
      localStorage.setItem('TIM_INIT', '0')
    }

    return {
      chat,
      login,
      logout,
      destroy
    }
  },
  {
    share: {
      enable: true,
      initialize: false
    }
  }
)
